package com.cloud.service.impl;

import com.cloud.dto.InventoryResult;
import com.cloud.mapper.ProductLogMapper;
import com.cloud.mapper.ProductMapper;
import com.cloud.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.UUID;

@Service
public class ProductServiceImpl implements ProductService {
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private ProductLogMapper productLogMapper;

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public InventoryResult lock(String productId) {
        System.out.println("lock:" + productId);
        InventoryResult inventoryResult = new InventoryResult();
        try {

            String id = UUID.randomUUID().toString().replaceAll("-", "");
            // 模拟锁库存操作
            int i = productLogMapper.insertStockLog(id, productId, "插入产品:" + productId);
            int j = productMapper.updateStock(productId);
            if (i != 1 || j != 1) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                inventoryResult.setStatus("FAILED");
                inventoryResult.setMessage("商品创建失败:" + productId);
                inventoryResult.setSku(productId);
                return inventoryResult;
            }
            inventoryResult.setStatus("SUCCESS");
            inventoryResult.setMessage("商品创建成功:" + productId);
            inventoryResult.setSku(productId);
            return inventoryResult;
        } catch (Exception e) {
            // 手动标记事务为回滚状态
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            inventoryResult.setStatus("FAILED");
            inventoryResult.setMessage("商品创建失败:" + productId);
            inventoryResult.setSku(productId);
            return inventoryResult;
        }
    }
}
